package com.madev.isellcrazyitems;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.madev.isellcrazyitems.entity.Product;
import com.madev.isellcrazyitems.entity.Statement;
import com.madev.isellcrazyitems.handler.DatabaseHandler;
import com.madev.sales.R;

public class ViewRecord extends Activity {

	private class ListAdapter extends BaseAdapter {

		LayoutInflater inflater;
		ViewHolder viewHolder;

		public ListAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return _productlist.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			convertView = inflater.inflate(R.layout.listview_row, null);
			viewHolder = new ViewHolder();

			viewHolder.txt_pname = (TextView) convertView
					.findViewById(R.id.txtdisplaypname);
			viewHolder.txt_pprice = (TextView) convertView
					.findViewById(R.id.txtdisplaypprice);
			viewHolder.txt_pstock = (TextView) convertView
					.findViewById(R.id.txtdisplaystock);
			viewHolder.txtidno = (TextView) convertView
					.findViewById(R.id.txtdisplaypid);
			viewHolder.prodImg = (ImageView) convertView
					.findViewById(R.id.prodImg);
			viewHolder.progBar = (ProgressBar) convertView
					.findViewById(R.id.progBar);
			convertView.setTag(viewHolder);
			viewHolder.txt_pname.setText(_productlist.get(position)
					.getProductName().trim());
			viewHolder.txt_pprice.setText(_productlist.get(position)
					.getProductPrice().trim());
			viewHolder.txt_pstock.setText(_productlist.get(position)
					.getProductStock().trim());
			viewHolder.txtidno.setText(_productlist.get(position)
					.getProductID().trim());

			// Load bitmap from internet
			URL onLineURL;
			try {
				onLineURL = new URL(_productlist.get(position)
						.getProductImagePath().trim());
				new MyNetworkTask(viewHolder.prodImg, viewHolder.progBar)
						.execute(onLineURL);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}

			final int temp = position;
			(convertView.findViewById(R.id.btn_update))
					.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {

							String _productid = String.valueOf(_productlist
									.get(temp).getProductID());
							String _productname = _productlist.get(temp)
									.getProductName();
							String _productprice = _productlist.get(temp)
									.getProductPrice();
							String _productstock = _productlist.get(temp)
									.getProductStock();
							String _productimagepath = _productlist.get(temp)
									.getProductImagePath();

							Intent intent = new Intent(ViewRecord.this,
									AddUpdateValues.class);

							Bundle bundle = new Bundle();
							bundle.putString("id", _productid);
							bundle.putString("name", _productname);
							bundle.putString("price", _productprice);
							bundle.putString("stock", _productstock);
							bundle.putString("image", _productimagepath);
							intent.putExtras(bundle);
							startActivity(intent);

						}
					});

			(convertView.findViewById(R.id.btn_delete))
					.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {

							AlertDialog.Builder alertbox = new AlertDialog.Builder(
									ViewRecord.this);
							alertbox.setCancelable(true);
							alertbox.setMessage("Are you sure you want to delete ?");
							alertbox.setPositiveButton("Yes",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface arg0, int arg1) {

											Log.i(">>>TEMP>>>", temp + "");
											Log.i(">>>getIdno>>>>>>",
													_productlist.get(temp)
															.getProductID()
															.trim());
											System.out
													.println(">>>getIdno>>>>>>"
															+ _productlist
																	.get(temp)
																	.getProductID()
																	.trim());

											db.removeProduct(_productlist
													.get(temp).getProductID()
													.trim());

											Statement st = new Statement();
											st.statement = ("DELETE FROM Products WHERE productIdNo='"
													+ _productlist.get(temp)
															.getProductID()
															.trim() + "';");
											db.addStatement(st);

											ViewRecord.this.onResume();

											Toast.makeText(
													getApplicationContext(),
													"Record Deleted.",
													Toast.LENGTH_SHORT).show();

										}

									});
							alertbox.setNegativeButton("No",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface arg0, int arg1) {

										}
									});
							alertbox.show();
						}
					});
			return convertView;

		}
	}

	private class ViewHolder {
		public ProgressBar progBar;
		TextView txt_pname;
		TextView txt_pprice;
		TextView txtidno;
		TextView txt_pstock;
		ImageView prodImg;
	}

	private ListView listview;
	TextView totalrecords;
	Button search;
	DatabaseHandler db;
	EditText searchet;
	private RadioButton idrb, namerb, stockrb;

	public ArrayList<Product> _productlist = new ArrayList<Product>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.viewrecord);
		totalrecords = (TextView) findViewById(R.id.totalrecords);
		listview = (ListView) findViewById(R.id.listview);
		search = (Button) findViewById(R.id.searchBtn);
		searchet = (EditText) findViewById(R.id.searchEt);
		idrb = (RadioButton) findViewById(R.id.idRb);
		namerb = (RadioButton) findViewById(R.id.nameRb);
		stockrb = (RadioButton) findViewById(R.id.stockRb);

		search.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String searchterm = searchet.getText().toString();
				String type = "";

				if (idrb.isChecked()) {
					type = "id";
				} else if (namerb.isChecked()) {
					type = "name";
				} else if (stockrb.isChecked()) {
					type = "stock";
				}

				_productlist.clear();

				db = new DatabaseHandler(getApplicationContext());
				db.getWritableDatabase();
				ArrayList<Product> product_list = db.getSearched(type,
						searchterm);

				for (int i = 0; i < product_list.size(); i++) {

					String tidno = product_list.get(i).getProductID();

					System.out.println("tidno>>>>>" + tidno);
					String tname = product_list.get(i).getProductName();
					String tprice = product_list.get(i).getProductPrice();
					String tstock = product_list.get(i).getProductStock();
					String turl = product_list.get(i).getProductImagePath();

					Product _ProductModel = new Product();
					_ProductModel.setProductStock(tstock);
					_ProductModel.setProductID(tidno);
					_ProductModel.setProductName(tname);
					_ProductModel.setProductPrice(tprice);
					_ProductModel.setProductImagePath(turl);

					_productlist.add(_ProductModel);
				}

				totalrecords.setText("Total Records: " + _productlist.size());
				listview.setAdapter(new ListAdapter(ViewRecord.this));
				db.close();

				Toast.makeText(getApplicationContext(), "Search Done",
						Toast.LENGTH_SHORT).show();

			}
		});

	}

	private class MyNetworkTask extends AsyncTask<URL, Void, Bitmap> {

		ImageView tIV;
		ProgressBar pb;

		public MyNetworkTask(ImageView iv, ProgressBar progBar) {
			tIV = iv;
			pb = progBar;
		}

		@Override
		protected Bitmap doInBackground(URL... urls) {

			Bitmap networkBitmap = null;

			URL networkUrl = urls[0]; // Load the first element
			try {
				networkBitmap = BitmapFactory.decodeStream(networkUrl
						.openConnection().getInputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}

			return networkBitmap;
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			tIV.setImageBitmap(result);
			pb.setVisibility(View.INVISIBLE);
		}

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		_productlist.clear();

		db = new DatabaseHandler(getApplicationContext());
		db.getWritableDatabase();
		ArrayList<Product> product_list = db.getProducts();

		for (int i = 0; i < product_list.size(); i++) {

			String tidno = product_list.get(i).getProductID();

			System.out.println("tidno>>>>>" + tidno);
			String tname = product_list.get(i).getProductName();
			String tprice = product_list.get(i).getProductPrice();
			String tstock = product_list.get(i).getProductStock();
			String turl = product_list.get(i).getProductImagePath();

			Product _ProductModel = new Product();
			_ProductModel.setProductStock(tstock);
			_ProductModel.setProductID(tidno);
			_ProductModel.setProductName(tname);
			_ProductModel.setProductPrice(tprice);
			_ProductModel.setProductImagePath(turl);

			_productlist.add(_ProductModel);
		}
		totalrecords.setText("Total Records: " + _productlist.size());
		listview.setAdapter(new ListAdapter(this));
		db.close();

	}

}
